<?php 
/**
 * The functions library  for Amawal.
 *
 * Contains all functions makin site run
 */
 

// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_check-entry-duplication', 'entry_is_duplicate' );
add_action( 'wp_ajax_check-entry-duplication', 'entry_is_duplicate' );
 
function entry_is_duplicate($word = false, $output_type = false) 
{	
	// if name is not supplied, then it is called by ajax
	if(!$word) $word = $_POST['word'];
	
	$output = array();
	
	$permalink = '';
	
	$args = array(
	  'name' => $word,
	  'post_type' => 'post',
	  'post_status' => 'publish',
	  'posts_per_page' => 1
	);
	
	$query  = new WP_Query($args);
	
	if( $query ->have_posts() ) {
		while ($query->have_posts()) : $query->the_post(); 
			$permalink = get_permalink();
			$output = array('status'=>'is_duplicate', 'msg'=> sprintf(  __( 'The entry <strong>"%1$s"</strong> exists already in Amawal! Think of adding a comment to the entry <a href="%2$s#add_new_comment">"%3$s"</a> in its comments page instead.', ns_text_domaine), $word, get_permalink(), $word ));
		endwhile;
		  
	} else
	{
		$output = array('status'=>'is_not_duplicate', 'msg'=> '' );
	}
	
	wp_reset_query();  // Restore global post data stomped by the_post().
	
	if( $output_type == 'bol' ) 
	{
		if($output['status'] == 'is_duplicate')
			return $output;
		else
			return false;
		
	} else
			echo json_encode( array('status'=>$output['status'], 'msg'=> $output['msg']) );
	
	die();
}


/**
 * Redirects people from the janrain engage to user accounts instead the admin dashboard
 *
 * @since Amawal 1.0
 */
function profile_redirect() {
	global $current_user;
	if( !current_user_can('administrator') )
	{
		 wp_redirect( home_url().'/my_account' );
  		exit();
	}
}
add_action('admin_init', 'profile_redirect');

global $current_user;
if( !current_user_can('administrator') )
{
	 rpx_set_redirect(home_url().'/my_account');
}


/**
 * Register our sidebars and widgetized areas.
 *
 * @since Amawal 1.0
 */
function amawal_widgets_init() {

	register_sidebar( array(
		'name' => 'Home right sidebar',
		'id' => 'home_right_1',
		'before_widget' => '<div>',
		'after_widget' => '</div>',
		'before_title' => '<h2 class="rounded">',
		'after_title' => '</h2>',
	) );

	register_sidebar( array(
		'name' => 'Janrain widget',
		'id' => 'janrain_widget',
		'before_widget' => '<div style="display:none">',
		'after_widget' => '</div>',
		'before_title' => '',
		'after_title' => '',
	) );
}
add_action( 'widgets_init', 'amawal_widgets_init' );

 
/**
 * CHANGE LOCAL LANGUAGE.
 */

/*
 * must be called before load_theme_textdomain()
 * default local is en_US
 * cookie is kept for 14 days
 *
 * @since Twenty Eleven 1.0
 */
function ns_localization( $locale )
{
	if ( is_admin() ) {
		return 'en_US';
	} else {
		
		// fast hack to bypass the warning headers sent
		//error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
		if( $_GET['l'] ){
			setcookie("amawal_language", $_GET['l'], time() + 1209600, COOKIEPATH, COOKIE_DOMAIN, false, false);
			if ( SITECOOKIEPATH != COOKIEPATH )
				setcookie("amawal_language", $_GET['l'], time() + 1209600, SITECOOKIEPATH, COOKIE_DOMAIN, false, false);
			return $_GET['l'];
		}
		else {
			if ( isset($_COOKIE['amawal_language']) )
				return $_COOKIE['amawal_language'];
			else 
				return 'en_US';
		}
	}
}
add_filter( 'locale', 'ns_localization' );

// SET THEME LANGUAGES DIRECTORY
// Theme translations are filed in the "{theme_name}/languages/" directory
// Wordpress translations are filed in the "wp-content/languages/" directory
load_theme_textdomain( ns_text_domaine, ns_languages );
	

/**
 * echo get local
 *
 * @since 1
 *
 * @return string: echo localized URL
 */
function _egl()
{	
	echo get_locale();
}

/**
 * echo get local
 *
 * @since 1
 *
 * @return string: echo localized URL
 */
function _gl()
{	
	return get_locale();
}

/**
 * echo images directory
 *
 * @since 1
 *
 * @return string: echoes the path to images in the theme directory
 */
function e_img()
{	
	echo ns_theme_path.'/images/';
}

/**
 * return images directory
 *
 * @since 1
 *
 * @return string: echoes the path to images in the theme directory
 */
function r_img()
{	
	return ns_theme_path.'/images/';
}

// Contact admin
function amawal_mail() 
{
	//Set vars
	$admin_email = get_option('admin_email');
	$author = esc_attr( $_POST['author'] );
	$author_email = esc_attr( $_POST['author_email'] );
	$author_message = esc_attr( $_POST['author_message'] );
	$subject = esc_attr($_POST['author']).' contacted you through np.ma';
	
	$mailto = $admin_email;	   	
	
    $headers = 'From: '.$author.' <'.$author_email.'>' . "\r\n";
    $headers .= 'Reply-To: '.$author.' <'.$author_email.'>' . "\r\n";
	
	// Checks
	if( !is_email($author_email) ) return false;		

    $message  = 'You are contacted by: '.$author."\r\n\r\n";
    $message  .= $author_message. "\r\n\r\n\r\n\r\n";
	$message .= "Sent by IP Address: ".amawal_get_ip()."\r\n\r\n"; 

    // ok let's send the email
	return wp_mail($mailto, $subject, $message, $headers);
}

// get the visitors IP for security tracking
function amawal_get_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {  //check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  //to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

if ( ! function_exists( 'ns_build_alphabet_menu' ) ):
/**
 * Output the alphabet both latin and tifinaghe
 *
 * @since Twenty Eleven 1.0
 */
function ns_build_alphabet_menu( $type = 'li' ) 
{
	$home_url = home_url();
	$len = count( generate_alphabet() );
	
	foreach ( generate_alphabet() as $index => $v)
	{
		$class = '';
		
		if ($index == 0) $class = ' class="first"';
		
		if($type == 'li')
			echo '<li'.$class.'><a href="'. $home_url .'/entry/'. mb_strtolower(html_entity_decode($v[0], ENT_QUOTES, 'UTF-8')) .'/"><span>'. mb_convert_case($v[0], MB_CASE_UPPER, "UTF-8") .'</span><span class="tz">'.mb_convert_case($v[1], MB_CASE_UPPER, "UTF-8") .'</span></a></li>';
	}
}
endif;



if ( ! function_exists( 'get_post_id_by_slug' ) ):
/**
 * Get a WordPress Page ID with the Slug
 *
 * @since Twenty Eleven 1.0
 */
function get_post_id_by_slug($the_slug) 
{
	$args = array(
		'name' => $the_slug,
		'post_type' => 'post',
		'post_status' => 'publish',
		'showposts' => 1,
		'caller_get_posts'=> 1
	);
	
	$my_posts = get_posts($args);
	
	if( $my_posts )
		return $my_posts[0]->ID;
	else
		return false;
    
}
endif; // get_post_id_by_slug



if ( ! function_exists( 'ns_auth_redirect_login' ) ):
/**
 * Checks if a user is logged in, if not redirect them to the login page
 *
 * @since Twenty Eleven 1.0
 */
function ns_auth_redirect_login() 
{
	if ( !is_user_logged_in() ) {
		nocache_headers();
		wp_redirect(get_option('siteurl') . '/login?redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
        exit();
	} 
    
}
endif; // ns_auth_redirect_login



if ( ! function_exists( 'ns_add_word' ) ):
/**
 * Add new word to database
 *
 * @since Twenty Eleven 1.0
 */
function ns_add_word( $post, $wp_error = '') 
{
	// remove begining and white spaces
	$post['word'] = trim($post['word']);
	
	// prepare error engin
	if ( empty($wp_error) )
		$wp_error = new WP_Error();
		
	// Does he have the previliges?
	if( !current_user_can( 'read' )){
		$wp_error->add('acess_forbidden', __('<strong>ERROR</strong>: You do not have enough access privileges for this operation!', ns_text_domaine));
		return $wp_error;
	}
	
	// Are characters allowed?
	$allowed = mb_convert_case(ns_allowed_chars().' ', MB_CASE_LOWER, "UTF-8"); // add a space too!
	$word = mb_convert_case($post['word'], MB_CASE_LOWER, "UTF-8");
	
	// Are the title characters allowed?
	$chars = array();
	foreach (preg_split('//u', $word) as $c) {
			$chars[] = $c; 
	  if (mb_strlen($c) !== 0 && mb_strpos($allowed, mb_strtolower($c)) === FALSE) {
		  $wp_error->add('wrong_word', sprintf( __( '<strong>ERROR</strong>: The character %1$s in %2$s is not allowed!', ns_text_domaine ), mb_strtolower($c), $word ));
		  return $wp_error;
	  }
	}
		
	// Is the category correct?
	$category = term_exists(  ns_word_initials($chars), 'category' );
	if(!$category){
		$wp_error->add('category_not_found', 
					printf( __('-%s- in [%s] is not found as a category in %s', ns_text_domaine), ns_word_initials($chars), $post['word'], $allowed)
		);
		
		return $wp_error;
	}
		
	// Is it a duplicate post?
	$is_duplicate = entry_is_duplicate($word, 'bol');
	if( $is_duplicate ){
		$wp_error->add('word_is_duplicate', $is_duplicate['msg']);
		return $wp_error;
	}
	
	// Create post object
	$args = array(
		'post_title' => $word,
		'post_content' => $post['content'],
		'post_status' => 'publish',
		'post_author' => get_current_user_id(),
		'post_category' => array( $category['term_id'] )
	);
	
	// Insert the post into the database.. Weeooohh!
	$post_ID = wp_insert_post( $args );
	
	// update translation custom fields
	$i = 1;
	foreach( $post['translation_language'] as $translation_language){
		if( $translation_language != '0' )
			add_post_meta($post_ID, 'translation_'.$translation_language, $post['translation'][$i] );
		$i++;
	}
	
	// update region custom fields
	add_post_meta($post_ID, 'meta_word_region', $post['meta_word_region']);
	
	// update relation custom fields
	if( $post['action'] == 'add_relation' )
	{
		if( $post['relation_type'] != '0' )
		{
			// update new post
			add_post_meta($post_ID, 'relation_type_'.$post['relation_type'], $post['relative_post_id']);
			
			// update old post
			add_post_meta($post['relative_post_id'], 'relation_type_'.$post['relation_type'], $post_ID);
		}	
	}
		
	if( $post['part_of_speech'] != '0' )
		add_post_meta($post_ID, 'part_of_speech', $post['part_of_speech']);
		
	if( $post['part_of_speech'] == 'n' )
		add_post_meta($post_ID, 'plural_form', $post['plural_form']);	
	
	return $post_ID;
  
  
/*	$post = array(
		'ID' => [ <post id> ] //Are you updating an existing post?
		'menu_order' => [ <order> ] //If new post is a page, sets the order should it appear in the tabs.
		'comment_status' => [ 'closed' | 'open' ] // 'closed' means no comments.
		'ping_status' => [ 'closed' | 'open' ] // 'closed' means pingbacks or trackbacks turned off
		'pinged' => [ ? ] //?
		'post_author' => [ <user ID> ] //The user ID number of the author.
		'post_category' => [ array(<category id>, <...>) ] //Add some categories.
		'post_content' => [ <the text of the post> ] //The full text of the post.
		'post_date' => [ Y-m-d H:i:s ] //The time post was made.
		'post_date_gmt' => [ Y-m-d H:i:s ] //The time post was made, in GMT.
		'post_excerpt' => [ <an excerpt> ] //For all your post excerpt needs.
		'post_name' => [ <the name> ] // The name (slug) for your post
		'post_parent' => [ <post ID> ] //Sets the parent of the new post.
		'post_password' => [ ? ] //password for post?
		'post_status' => [ 'draft' | 'publish' | 'pending'| 'future' | 'private' ] //Set the status of the new post. 
		'post_title' => [ <the title> ] //The title of your post.
		'post_type' => [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] //You may want to insert a regular post, page, link, a menu item or some custom post type
		'tags_input' => [ '<tag>, <tag>, <...>' ] //For tags.
		'to_ping' => [ ? ] //?
		'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies. 
	);*/  
    
}
endif; // ns_add_word


/**
 * Get the beggining of the word
 *
 * @since Twenty Eleven 1.0
 */
function ns_word_initials( $word ) 
{	
	if( ($word[1] == 'g' || $word[1] == 'k') && $word[2] == 'w' )
	{
		return $word[1].$word[2];
	}
	else
	{
		return $word[1];
	}
}


/**
 * Get a string of the allowed characters
 *
 * @since Twenty Eleven 1.0
 */
function ns_allowed_chars() 
{
	$chars = '';
	foreach (generate_alphabet() as $category ) 
	{	
		$chars .= $category[0];
		//$chars .= html_entity_decode($category[0], ENT_QUOTES, 'UTF-8');
	}
	return $chars;
}



if ( ! function_exists( 'ns_comments' ) ) :
/**
 * Template for comments and pingbacks.
 *
 * To override this walker in a child theme without modifying the comments template
 * simply create your own twentyeleven_comment(), and that function will be used instead.
 *
 * Used as a callback by wp_list_comments() for displaying the comments.
 *
 * @since Twenty Eleven 1.0
 */
function ns_comments( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	
	$ns_is_rtl = false;
	if ( ns_is_there_rtl_chars( get_comment_text() ) ) $ns_is_rtl = true;
		
	switch ( $comment->comment_type ) :
		case 'pingback' :
		case 'trackback' :
	?>
			<li class="post pingback">
				<p><?php _e( 'Pingback:', ns_text_domaine ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit', ns_text_domaine ), '<span class="edit-link">', '</span>' ); ?></p>
	<?php
			break;
		default :
	?>
			<li class="rounded" id="li-comment-<?php comment_ID(); ?>">
				<div class="comment_wrapper">
					<a href="<?php get_comment_link( $comment->comment_ID ); ?>" class="comment_image">
						<?php
							$avatar_size = 32;
							if ( '0' != $comment->comment_parent )
								$avatar_size = 16;
	
							echo get_avatar( $comment, $avatar_size );
	
							
						?>
					</a>
					<div class="comment_container <?php if( $ns_is_rtl ) echo 'rtl'; else echo 'ltr'; ?>">
						<?php echo get_comment_author_link(); ?>
						<span><?php comment_text(); ?></span>
						<div class="timestamp">
						<?php 
								/* translators: 1: comment author, 2: date and time */
								echo sprintf( '<time pubdate datetime="%2$s">%3$s</time>',
										esc_url( get_comment_link( $comment->comment_ID ) ),
										get_comment_time( 'c' ),
										/* translators: 1: date, 2: time */
										sprintf( __( '%1$s at %2$s', ns_text_domaine ), get_comment_date(), get_comment_time() )
									);
						?>
						<?php edit_comment_link( __( 'Edit', ns_text_domaine ), '<span class="ltr">', '</span>' ); ?>
						</div>
					</div>
				</div>			
	<?php
			break;
	endswitch;
}
endif; // ends check for ns_comments()


/**
 * Is There RTL Chars
 * Check if there RTL characters (Arabic, Persian, Hebrew)
 * 
 * @author  Khaled Attia (http://twitter.com/khal3d)
 * @param   String  $string
 * @return  bool
 */ 
function ns_is_there_rtl_chars( $string = '' )
{
    $rtl_chars_pattern = '/[\x{0590}-\x{05ff}\x{0600}-\x{06ff}]/u';
    return preg_match($rtl_chars_pattern, $string);
}


/**
 * Is There Tifinagh Chars
 * Check if there Tifinagh characters (Unicode range from 2d30-2d7f)
 * 
 * @author  Abdessamad Idrissi (www.amawal.net)
 * @param   String  $string
 * @return  bool
 */ 
function ns_is_there_tz_chars( $string = '' )
{
    $rtl_chars_pattern = '/[\x{2d30}-\x{2d7f}]/u';
    return preg_match($rtl_chars_pattern, $string);
}



/**
 * Translate meta key
 * 
 */ 
function ns_decode_meta( $value )
{
	global $meta_word_region_array;
	
	$key = 'name';
	
    $echo = '';
	
	foreach ($meta_word_region_array as $subarray)
	{
		if ($subarray[$key] == $value) $echo .= $subarray['value'];
	}
	
	if( empty($echo) )
		return false;
	else
		return $echo;
}

/**
 * URL localizer
 *
 * @since 1
 *
 * @echo string: echo localized URL
 */
function _el($perfix = '?', $l = null )
{	
	if( $l )
	 echo $perfix.'l='.$l;
	else
	 echo $perfix.'l='.get_locale();
}